﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using NLog;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Reflection;

namespace TestReatXML
{
    public partial class FrmMain : Form
    {

        private static Logger _logger = null;


        FrmSettings settingsDialog = new FrmSettings();
        public FrmMain()
        {
            InitializeComponent();
            if (_logger == null)
            {
                //string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                //NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(assemblyFolder + "\\NLog.config", true);
                _logger = LogManager.GetCurrentClassLogger();
            }
        }

        private void btnSertPath_Click(object sender, EventArgs e)
        {
            settingsDialog.ShowDialog();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            validateSettings();
        }

        private Boolean validateSettings()
        {
            try
            {
                Properties.Settings settings = Properties.Settings.Default;
                SettingsValidator.validate(settings);
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error( ex);
                settingsDialog.ShowDialog();
                return false;
            }
        }

        private void btnDownloadXml_Click(object sender, EventArgs e)
        {
            _logger.Info("Validating settings");
            if (!validateSettings())
            {
                return;
            }
            Properties.Settings settings = Properties.Settings.Default;
            try
            {
                DateTime start_time = DateTime.Now;
                StringWriter strWriter = new StringWriter();
                _logger.Info("Starting download");
                Dictionary<int, string> values = XMLDownloader.download(settings.certificate_path, settings.pwd, settings.url, settings.xml_output, start_time, strWriter);
                _logger.Info("End download");
                DateTime end_time = DateTime.Now;
                _logger.Info("Starting execute db");
                DBOperation.execute(settings.db_connection, settings.autoincrement_retrive, start_time, end_time, values);
                _logger.Info("End execute db");
                DateTime full_time = DateTime.Now;
                String resultTime = "Download time=" + getTimeDifference(start_time, end_time) + ", DB insert time=" + getTimeDifference(end_time, full_time)
                        + ", DB insert time=" + getTimeDifference(start_time, full_time);
                String file_saved_in = start_time.ToString(SettingsValidator.date_format);
                file_saved_in = "File saved in " + Path.GetFullPath(settings.xml_output + "\\" + file_saved_in + ".xml");
                String message = "Retrive data success!!!\n" + resultTime + "\n" + file_saved_in;
                _logger.Info(message);
                MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
                _logger.Error(ex);
            }

        }
        private String getTimeDifference(DateTime start, DateTime end)
        {
            int diff = (int)((TimeSpan)(end - start)).TotalSeconds;
            String result = "";
            if (diff > 60)
            {
                int minutes = (int)((double)diff / 60.0);
                int seconds = (diff - minutes * 60);
                result = minutes + " minutes";
                if (seconds > 0)
                    result += " and " + seconds + " seconds";
            }
            else
                result = diff + " seconds";
            return result;
        }
    }
}
